package com.xyy.controller;

import com.xyy.common.Result;
import com.xyy.dto.ActivityCreateDTO;
import com.xyy.dto.ActivityUpdateDTO;
import com.xyy.entity.Activity;
import com.xyy.service.ActivityService;
import com.xyy.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 活动管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/activity")
public class ActivityController {
    
    @Resource
    private ActivityService activityService;
    
    @Autowired
    private FileService fileService;
    
    /**
     * 创建活动
     */
    @PostMapping("/create")
    public Result<Activity> createActivity(@Valid @RequestBody ActivityCreateDTO createDTO, 
                                         HttpServletRequest request) {
        try {
            Long adminId = (Long) request.getAttribute("userId");
            Activity activity = activityService.createActivity(createDTO, adminId);
            return Result.success(activity);
        } catch (Exception e) {
            log.error("创建活动失败", e);
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 删除活动
     */
    @DeleteMapping("/{id}")
    public Result<Boolean> deleteActivity(@PathVariable Long id, 
                                        HttpServletRequest request) {
        try {
            Long adminId = (Long) request.getAttribute("userId");
            boolean success = activityService.deleteActivity(id, adminId);
            if (success) {
                return Result.success(true);
            } else {
                return Result.error("活动不存在或无权限删除");
            }
        } catch (Exception e) {
            log.error("删除活动失败", e);
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 更新活动
     */
    @PutMapping("/update")
    public Result<Activity> updateActivity(@Valid @RequestBody ActivityUpdateDTO updateDTO, 
                                         HttpServletRequest request) {
        try {
            Long adminId = (Long) request.getAttribute("userId");
            Activity activity = activityService.updateActivity(updateDTO, adminId);
            return Result.success(activity);
        } catch (Exception e) {
            log.error("更新活动失败", e);
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 上传活动封面
     */
    @PostMapping("/{id}/uploadCover")
    public Result<Map<String, String>> uploadCover(@PathVariable Long id,
                                                  @RequestParam("cover") MultipartFile file,
                                                  HttpServletRequest request) {
        try {
            Long adminId = (Long) request.getAttribute("userId");
            
            // 验证文件
            if (file.isEmpty()) {
                return Result.error("请选择要上传的文件");
            }
            
            // 验证文件类型
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null || !isValidImageFile(originalFilename)) {
                return Result.error("只支持jpg, jpeg, png, gif, bmp格式的图片");
            }
            
            // 验证文件大小（5MB）
            if (file.getSize() > 5 * 1024 * 1024) {
                return Result.error("文件大小不能超过5MB");
            }
            
            // 上传封面到MinIO
            String coverUrl = activityService.uploadCover(id, adminId, originalFilename, file.getBytes());
            
            Map<String, String> result = new HashMap<>();
            result.put("coverUrl", coverUrl);
            
            return Result.success("封面上传成功", result);
        } catch (Exception e) {
            log.error("活动封面上传失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 获取活动封面图片
     */
    @GetMapping("/cover/{filename}")
    public ResponseEntity<Resource> getActivityCover(@PathVariable String filename) {
        try {
            Resource resource = activityService.getActivityCover(filename);
            if (resource.exists() && resource.isReadable()) {
                return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + filename + "\"")
                    .contentType(MediaType.IMAGE_JPEG)
                    .body(resource);
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            log.error("获取活动封面失败: {}", e.getMessage());
            return ResponseEntity.notFound().build();
        }
    }
    
    /**
     * 获取活动列表（所有用户可见）
     */
    @GetMapping("/list")
    public Result<List<Activity>> getActivityList() {
        try {
            List<Activity> activities = activityService.getActivityList();
            return Result.success(activities);
        } catch (Exception e) {
            log.error("获取活动列表失败", e);
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 根据ID获取活动详情
     */
    @GetMapping("/{id}")
    public Result<Activity> getActivityById(@PathVariable Long id) {
        try {
            Activity activity = activityService.getActivityById(id);
            if (activity != null) {
                return Result.success(activity);
            } else {
                return Result.error("活动不存在");
            }
        } catch (Exception e) {
            log.error("获取活动详情失败", e);
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 获取当前管理员创建的活动列表
     */
    @GetMapping("/admin/list")
    public Result<List<Activity>> getAdminActivityList(HttpServletRequest request) {
        try {
            Long adminId = (Long) request.getAttribute("userId");
            List<Activity> activities = activityService.getActivityListByAdminId(adminId);
            return Result.success(activities);
        } catch (Exception e) {
            log.error("获取管理员活动列表失败", e);
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 刷新活动封面URL
     */
    @PostMapping("/{id}/refreshCover")
    public Result<Map<String, String>> refreshCover(@PathVariable Long id) {
        try {
            String newCoverUrl = activityService.refreshActivityCoverUrl(id);
            if (newCoverUrl != null) {
                Map<String, String> result = new HashMap<>();
                result.put("coverUrl", newCoverUrl);
                return Result.success("封面URL刷新成功", result);
            } else {
                return Result.error("活动不存在或没有封面");
            }
        } catch (Exception e) {
            log.error("刷新活动封面URL失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 验证图片文件类型
     */
    private boolean isValidImageFile(String filename) {
        if (filename == null) {
            return false;
        }
        
        String lowerFilename = filename.toLowerCase();
        return lowerFilename.endsWith(".jpg") || 
               lowerFilename.endsWith(".jpeg") || 
               lowerFilename.endsWith(".png") || 
               lowerFilename.endsWith(".gif") || 
               lowerFilename.endsWith(".bmp");
    }
} 